<template>
    <div class="common courseAdd">
        <innerCommon 
            :location="location"
        >
            <div slot="right" class="top">
                <a-steps :current="current">
                    <a-step v-for="item in steps" :key="item.title" :title="item.title" />
                </a-steps>
                <a-button class="returnBack" type="primary" @click="returnBack()">返回</a-button>
            </div>
            <div slot="table" class="tableWrap">
                    <eform
                        :formData="formData"
                        class="form"
                        ref="form"
                        :fields="fields"
                        v-if="current==0&&(fields||type==0)"
                    >
                        <div slot="cover">
                            <eUpload
                                @getUrl="getUrl"
                                v-decorator="['cover',{rules: [{ required: true, message: '请上传封面' }]}]"
                                :imageUrl="imageUrl"
                                :size="'284*160'"
                            ></eUpload>
                        </div>
                        <div slot="major">
                            <a-select 
                                placeholder="专业方向" 
                                v-decorator="['major',{rules: [{ required: true, message: '请选择专业方向' }]}]"
                                @change="handleMajor($event,0)">
                                <a-select-option v-for="(item,index) in majorList" :key="index" :value="item.id">{{item.name}}</a-select-option>
                            </a-select>
                        </div>
                        <div slot="module" class="module">
                            <a-select 
                                placeholder="教学模块" 
                                v-decorator="['module',{rules: [{ required: true, message: '请选择教学模块' }]}]"
                                >
                                <a-select-option v-for="(item,index) in moduleList" :key="index" :value="item.id">{{item.name}}</a-select-option>
                            </a-select>
                            <a-button class="moduleManager activeBtn" @click="openModuleModal()">教学模块管理</a-button>
                        </div>
                        <div slot="briefIntro">
                            <a-textarea
                                v-decorator="['teacherInfo',{rules: [{ required: false, message: '请输入教师简介' }]}]"
                                placeholder="请输入教师简介"
                                :autosize="{ minRows: 4, maxRows: 6 }"
                            />
                        </div>
                        <div slot="auth">
                            <eSilder
                                v-decorator="['authentation',{rules: [{ required: true, message: '请选择权限' }]}]"
                                @changeAuth="changeAuth"
                                :defaultAuthValue="defaultAuthValue"
                            ></eSilder>
                        </div>
                    </eform>
                    <div class="courseInfo" v-if="current==1">
                        <eQuill
                            @getQuillContent="getQuillContent"
                            v-decorator="['courseInfo',{rules: [{ required: true, message: '请输入内容' }]}]"
                            :defaultData="quillInfo"
                        ></eQuill>
                    </div>
                    <div v-if="current==2" class="catalog">
                        <div v-if="catalog.length==0" class="empty">
                            <a-button type="primary" @click="openCata(0)">新增课程内容</a-button>
                            <a-empty
                                description="暂无内容"
                            ></a-empty>
                        </div>
                        <div v-else class="cata">
                            <div ref='prismPlayer'>
                                
                            </div>
                            <div class="cataTop">
                                课程目录（提示：支持最多上传100节，每节最多10个任务）
                            </div>
                            <div class="cataBox" v-for="(item,index) in catalog" :key="index">
                                <div class="cataTitle" @click="currentCataId=item.id">
                                    <div>
                                        <b>第{{exchangeIndex(index+1)}}节</b>
                                        {{item.title}}  
                                    </div>
                                    <div>
                                        
                                        <span @click="openCata(1,item.rank)">插入</span>
                                        <span @click="editChapter(item)">修改</span>
                                        <confirmBox
                                            @handleOk="deleteChapter(item.id)"
                                            :typeName="'删除'"
                                            :noticeInfo="item.title"
                                            :noticeType="'章节'"
                                        ></confirmBox>
                                        <span @click="openTaskModal(item)">添加学习任务</span>
                                    </div>
                                </div>
                                <div class="taskList" v-if="currentCataId==item.id">
                                    <div class="taskBox" v-for="(value,taskIndex) in item.tasks" :key="taskIndex">
                                        <div>
                                            <span v-if="value.type==0">【视频】</span>
                                            <span v-else-if="value.type==1">【资料】</span>
                                            <span v-else-if="value.type==2">【习题】</span>
                                            <span v-else-if="value.type==3">【考试】</span>
                                            <span v-else>【题库训练】</span>
                                            {{value.title}}
                                        </div>
                                        <div class="right">
                                            <span @click="previewTask(value)">预览</span>
                                            <span @click="openTaskModal(item,value.rank)">插入</span>
                                            <span v-if="item.tasks.length>1&&taskIndex!=0" @click="taskMove(value.id,'up')">上移</span>
                                            <span v-if="item.tasks.length>1&&taskIndex!=item.tasks.length-1" @click="taskMove(value.id,'down')">下移</span>
                                            <span @click="editTask(value)">修改</span>
                                            <confirmBox
                                                @handleOk="deleteTask(value.id)"
                                                :typeName="'删除'"
                                                :noticeInfo="value.title"
                                                :noticeType="'任务'"
                                            ></confirmBox>
                                            <span v-if="value.type!=3" @click="setFree(value)">{{value.isFree==0?'设为试看':'取消试看'}}</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <a-button class="bottomBtn activeBtn" @click="openCata(0)">新增章节</a-button>
                    </div>
                    <div class="steps-action" >
                        <a-button v-if="current > 0" @click="prev">
                            上一步
                        </a-button>
                        <a-button
                            v-if="current == steps.length - 1"
                            type="primary"
                            @click="save()"
                            style="margin-left: 8px"
                        >
                            完成
                        </a-button>
                        <a-button v-if="current < steps.length - 1" style="margin-left: 8px" type="primary" @click="next">
                            下一步
                        </a-button>
                        
                    </div>
            </div>
        </innerCommon>
        <!-- 添加章节模态框 -->
        <a-modal
            :title="isAddChapter==0?'新增':'修改'"
            :visible="cataModal"
            @ok="addCata()"
            @cancel="cataModal=false"
            okText="确认"
            :destroyOnClose='true'
            cancelText='取消'
            >
            <eform
                :formData="cataFormData"
                class="cataForm"
                ref="cataForm"
                :fields="catafields"
            >
            </eform>
        </a-modal>

        <!-- 添加学习任务弹框 -->
        <a-modal
            :title="isAddTask==0?title+' 新增任务':title+' 修改任务'"
            :visible="taskModal"
            @ok="addTask()"
            @cancel="cancelModal()"
            :confirm-loading="isLoading"
            okText="确认"
            :destroyOnClose='true'
            cancelText='取消'
            class="courseAddModal"
            width="800px"
            >
            <a-select 
                :value="selectTask" 
                @change="changeTask"
                class="selectTask"
                >
                <a-select-option v-for="(item,index) in taskTypeList" :key="index" :value="item.id">{{item.name}}</a-select-option>
            </a-select>
            <div v-if="selectTask==4" class="taskTypeTips">（整门课程仅且添加一个考试任务的时候显示在前台考试类课程中）</div>
            <a-select 
                :value="selectExamType" 
                @change="changeExamType"
                class="selectExamType"
                placeholder="考试类型" 
                v-if="selectTask==4"
                >
                <a-select-option v-for="(item,index) in ExamTypeList" :key="index" :value="item.id">{{item.name}}</a-select-option>
            </a-select>
            <eform
                :formData="taskFormData"
                class="taskForm"
                ref="taskForm"
                :fields="taskfields"
            >
           
                <div slot="taskType" class="taskType" v-decorator="['type',{rules: [{ required: true, message: '请选择任务类型' }]}]">
                </div>
                <div slot="examTime">
                    <div v-decorator="['examTime']">
                        <selectTime
                            @changeTime="changeTime"
                            :defaultTime="defaultTime"
                            @changeEndTime="defaultTime[1]=null"
                        ></selectTime>
                    </div>
                </div>
                <div slot="taskResource" v-decorator="['file',{rules: [{ required: true, message: '请上传资源' }]}]">
                    <uploadVideo @onUploadSucceed="onUploadSucceed" @waitUploading="waitUploading" v-if="fileType==1" @upload="isLoading=$event" @uploadSuccess="isLoading=$event"></uploadVideo>
                    <a-upload
                        v-else
                        name="file"
                        :multiple="true"
                        :data="{'type':taskType}"
                        :action="apiUrl+'manage/task/upload'"
                        :accept="accept"
                        :headers="headers"
                        @change="handleChange"
                        :remove="handleRemove"
                        :file-list="fileList"
                    >
                        <a-button :disabled="fileType?false:'disabled'"> <a-icon type="upload" /> 上传资源 </a-button>
                    </a-upload>

                </div>
                <div slot="test">
                    <a-textarea
                        placeholder="请输入说明"
                        v-decorator="['testInfo',{rules: [{ required: true, message: '请输入说明' }]}]"
                        :autosize="{ minRows: 4, maxRows: 9 }"
                    />
                </div>
                <div slot="exam" v-decorator="['paperId',{rules: [{ required: true, message: '请选择试题' }]}]">
                    <a-button @click="selectPaper()" v-if="paperOrItem">选择试题</a-button>
                    <a-button @click="selectItem()" v-else>选择题库</a-button>
                    <div 
                        v-if="selectPaperInfo" 
                        class="selectPaper"
                        >
                        <span>{{selectPaperInfo.title}}</span>
                        <span>
                            共{{selectPaperInfo.singleNum+selectPaperInfo.multiNum+selectPaperInfo.judgeNum+selectPaperInfo.operationNum}}题
                            <b class="deletePaper" @click="removePaper()">删除</b>
                        </span>
                    </div>
                </div>
                <div slot="examType" class="examType" v-decorator="['examType',{rules: [{ required: true, message: '请选择考试类型' }]}]">
                    
                </div>
                <div slot="operationExam">
                    <a-textarea
                        placeholder="注：实操考试采用虚拟仿真系统进行，请输入实操考试要求"
                        v-decorator="['operationInfo',{rules: [{ required: true, message: '请输入实操考试要求' }]}]"
                        :autosize="{ minRows: 4, maxRows: 9 }"
                    />
                </div> 
            </eform>
            
        </a-modal>

        <!-- 试题模态框 -->
        <a-modal
            :title="fileType==3?'我的测试':'我的考试'"
            :visible="paperModal"
            class='paperModal'
            @cancel="paperModal=false"
            :destroyOnClose='true'
            :footer="false"
            width="1100px"
            >
            <div class="body">
                <div class="header">
                    <majorModule
                        @submitSearch="submitSearch"
                    ></majorModule>
                </div>
                <a-table 
                    size="middle"
                    :columns="columns" 
                    :data-source="paperList" 
                    :pagination="pagination"
                    :rowKey="record=>record.id"
                    @change="changePage"
                    :locale="{'emptyText': '暂无数据'}"
                    bordered>
                    <div slot="major" slot-scope="index,record">
                        {{record.majors[0].name}}
                    </div>
                    <div slot="module" slot-scope="index,record">
                        {{record.majors[1].name}}
                    </div>
                    <div slot="operator" slot-scope="index,record">
                        {{record.operator.name}}
                    </div>
                    <div slot="questionType" slot-scope="index,record">
                        <a-tag>
                            单选{{record.singleNum}}
                        </a-tag>
                        <a-tag>
                            多选{{record.multiNum}}
                        </a-tag>
                        <a-tag>
                            判断{{record.judgeNum}}
                        </a-tag>
                        <!-- <a-tag>
                            实操{{record.operationNum}}
                        </a-tag> -->
                    </div>
                    <div slot="action" slot-scope="index,record" class="tableAction">
                        <span @click="previewTest(record.id)">预览</span>
                        <span @click="isSelect(record)">选中</span>
                    </div>
                </a-table>
            </div>
        </a-modal>

        <!-- 模块模态框 -->
        <a-modal
            title="模块管理"
            :visible="moduleModal"
            class='moduleModal'
            @cancel="cancelModule"
            :destroyOnClose='true'
            :footer="false"
            width="900px"
            >
            <div class="body">
                <div class='header'>
                    模块列表
                    <a-select 
                        style="width:300px"
                        :value="selectMajor"
                        defaultValue='请选择专业'
                        @change="handleMajor($event,1)">
                        <a-select-option v-for="(item,index) in majorList" :key="index" :value="item.id">{{item.name}}</a-select-option>
                    </a-select>
                    <a-button
                        type="primary"
                        style="float:right"
                        @click="openAddModuleModal()"
                        >添加模块</a-button>
                </div>
                <a-table 
                    size="middle"
                    :columns="moduleColumns" 
                    :data-source="moduleTableList" 
                    :pagination="modulePagination"
                    :rowKey="record=>record.id"
                    bordered
                >
                    <div slot="action" slot-scope="index,record" class="tableAction">
                        <span @click="editModule(record)">修改</span>
                        <confirmBox
                            @handleOk="deleteModule(record.id)"
                            :typeName="'删除'"
                            :noticeInfo="record.name"
                            :noticeType="'模块'"
                        ></confirmBox>
                    </div>
                </a-table>
            </div>
        </a-modal>
        <!-- 模块模态框 -->
        <a-modal
            :title="modulefields?'修改模块':'新增模块'"
            :visible="addModuleModal"
            class='moduleModal'
            @cancel="addModuleModal=false"
            :destroyOnClose='true'
            okText="确认"
            cancelText="取消"
            @ok="addModule()"
            >
            <eform
                :formData="moduleFormData"
                class="moduleForm"
                ref="moduleForm"
                :fields="modulefields"
            >
                <div slot="major">
                    <a-select 
                        placeholder="专业方向" 
                        :disabled="isSelectModule"
                        style="width:300px"
                        v-decorator="['major',{rules: [{ required: true, message: '请选择专业方向' }]}]"
                        @change="handleMajor($event,2)">
                        <a-select-option v-for="(item,index) in majorList" :key="index" :value="item.id">{{item.name}}</a-select-option>
                    </a-select>
                </div>
            </eform>
        </a-modal>
        <!-- 题库模态框 -->
        <a-modal
            :title="'选择题库'"
            :visible="selectItemModal"
            class='selectItem'
            @cancel="selectItemModal=false"
            :destroyOnClose='true'
            okText="确认"
            cancelText="取消"
            :footer="false"
            @ok="submitItem()"
            :width="1200"
            >
            <div class="itemTable">
                <div class="bar" style="margin-bottom:20px">
                    <majorModule
                        @submitSearch="submitItemSearch"
                    ></majorModule>
                </div>
                <div class="table">
                    <a-table 
                        size="middle"
                        :columns="itemColumns" 
                        :data-source="itemList" 
                        :pagination="itemPagination"
                        :rowKey="record=>record.id"
                        @change="changeItemPage"
                        :locale="{'emptyText': '暂无数据'}"
                        bordered>
                        <div slot="major" slot-scope="index,record">{{record.majors[0].name}}</div>
                        <div slot="module" slot-scope="index,record">{{record.majors[1].name}}</div>
                        <div slot="questionType" slot-scope="index,record">
                            <a-tag>
                                单选{{record.singleNum}}
                            </a-tag>
                            <a-tag>
                                多选{{record.multiNum}}
                            </a-tag>
                            <a-tag>
                                判断{{record.judgeNum}}
                            </a-tag>
                        </div>
                        <div slot="totalNum" slot-scope="index,record">
                            {{parseInt(record.singleNum)+parseInt(record.multiNum)+parseInt(record.judgeNum)}}
                        </div>
                        <div slot="action" class="tableAction" slot-scope="index,record">
                            <span @click="previewTest(record.id)">预览</span>
                            <span @click="isSelectItem(record)">选中</span>
                        </div>
                    </a-table>
                </div>
            </div>
        </a-modal>
    </div>
</template>
<script>
const moduleColumns=[
    {
        title: '序号',
        dataIndex: 'index',
        width:70
    },{
        title: '教学模块名称',
        dataIndex: 'name'
    },{
        title: '专业方向',
        dataIndex: 'major'
    },{
        title: '操作',
        scopedSlots: { customRender: 'action' },
        width:120
    }
]
const columns=[
    {
        title: '序号',
        dataIndex: 'index',
        width:70
    },{
        title: '试题名称',
        dataIndex: 'title',
    },{
        title: '所属专业',
        scopedSlots: { customRender: 'major' },
    },{
        title: '所属教学模块',
        scopedSlots: { customRender: 'module' },
    },{
        title: '题目类型和数量',
        scopedSlots: { customRender: 'questionType' },
        width:270
    },{
        title: '总分',
        dataIndex: 'totalScore',
        width:100
    },{
        title: '操作',
        scopedSlots: { customRender: 'action' },
        width:120
    }
]
const itemColumns=[
    {
        title: '序号',
        dataIndex: 'index',
        width:70
    },{
        title: '题库名称',
        dataIndex: 'title',
    },{
        title: '教学模块',
        scopedSlots: { customRender: 'major' },
    },{
        title: '专业方向',
        scopedSlots: { customRender: 'module' },
    },{
        title: '题目类型和数量',
        scopedSlots: { customRender: 'questionType' },
        width:270
    },{
        title: '总题数',
        scopedSlots: { customRender: 'totalNum' },
        width:100
    },{
        title: '操作',
        scopedSlots: { customRender: 'action' },
        width:120
    }
]
import moment from 'moment'
import selectTime from "@/components/common/selectTime"
import uploadVideo from "@/components/common/uploadVideo"
import majorModule from "@/components/common/majorModule"
import innerCommon from "@/components/common/innerCommon"
import eform from "@/components/common/form"
import eUpload from "@/components/common/eUpload"
import eSilder from "@/components/common/eSilder"
import eQuill from "@/components/common/eQuill"
import confirmBox from "@/components/common/confirmBox"
import {exchangeIndex} from "@/units/exchangeIndex.js"
import {
    getMajorListApi,
    submitCourseApi,
    updateCourseApi,
    getCourseDetailApi,
    addChapterApi,
    updateChapterApi,
    deleteChapterApi,
    addTaskApi,
    deleteTaskApi,
    updateTaskApi,
    moveTaskApi,
    getTestList,
    addModuleApi,
    deleteModuleApi,
    editTaskApi,
    editModuleApi,
    checkModuleApi,
    checkTitleExistApi,
    getQuestionList
} from "@/request/api"
export default {
    name:'courseAdd',
    components:{innerCommon,eform,eUpload,eSilder,eQuill,confirmBox,majorModule,uploadVideo,selectTime},
    created(){
        if(this.$route.query.id){
            this.courseId=this.$route.query.id
            this.editInit(this.courseId)
        }else{
            this.type=0
        }
        this.location=[{
            name:"教学课堂管理",
            path:''
        },{
            name:"课程管理",
            path:'/course'
        },{
            name:this.type==0?"新增课程":"修改课程",
            path:'/courseAdd'
        }]
        this.getToken(getMajorListApi,{},res=>{
            this.majorList=res.data
        })
    },
    watch:{
        courseId:function(val){
            this.editInit(val)
        }
    },
    beforeRouteEnter(to, from, next){
        next((vm)=>{
            if(from.path=='/previewVideo'){
                vm.current=2
            }
        })
    },
    data(){
        let validator=(length)=>{
        let validatorName=(rule,value,callback)=>{
            let check=()=>{
                if(value.length>(length||30)){
                     callback(new Error('字数过多，请重新输入'))  
                }
                this.getToken(checkTitleExistApi,{'title':value},res=>{
                    if(res.used){
                        callback(new Error('课程重名了'))
                    }else{
                        callback()
                    }
                })
            }
            if(this.fields){
                if(value!=this.fields.title){
                    check()
                }else{
                    callback()
                }
            }else{
                check()
            }
        }
        return validatorName
    }
        const formData=[
            {
                label:"课程名称",
                prop:"title",
                placeholder:'请输入课程名称（30个字符以内）',
                rules:[{required:true,message:'请输入课程名称'},{validator:validator(30)}],
            },{
                label:"课程封面",
                scopedSlots: { customRender: 'cover'},
            },{
                label:"专业方向",
                scopedSlots: { customRender: 'major'},
            },{
                label:"教学模块",
                scopedSlots: { customRender: 'module'},
            },{
                label:"授课教师",
                prop:"teacher",
                placeholder:'请输入授课教师',
                rules:[{required:true,message:'请输入授课教师'}],
            },{
                label:"教师简介",
                scopedSlots: { customRender: 'briefIntro'},
            },{
                label:"加入权限",
                scopedSlots: { customRender: 'auth'},
            }
        ]
        const cataFormData=[
            {
                label:"章节名称",
                prop:"chapter",
                placeholder:'请输入章节名称',
                rules:[{required:true,message:'请输入章节名称'}],
            }
        ]
        const taskFormData=[
            {
                label:"任务类型",
                scopedSlots: { customRender: 'taskType'},

            },{
                label:"任务名称",
                prop:"title",
                placeholder:'请输入任务名称',
                rules:[{required:true,message:'请输入任务名称'}],
            },{
                label:"资源上传",
                isVisible:false,
                scopedSlots: { customRender: 'taskResource'},
            },{
                label:"测试说明",
                isVisible:true,
                scopedSlots: { customRender: 'test'},
            },{
                label:"试题选择",
                isVisible:true,
                scopedSlots: { customRender: 'exam'},
            }
        ]
        const moduleFormData=[
            {
                label:"专业方向",
                scopedSlots: { customRender: 'major'},
            },{
                label:"模块名称",
                prop:"module",
                placeholder:'请输入模块名称',
                rules:[{required:true,message:'请输入模块名称'}],
            }
        ]
        return{
            itemColumns,
          
            validator,
            moduleFormData,
            exchangeIndex,
            cataFormData,
            taskFormData,
            formData,
            fields:null,
            location:[],
            current:0,
            imageUrl:'',
            accept:'.mp4',
            steps: [
                {
                title: '基本信息',
                content: '基本信息',
                },
                {
                title: '课程介绍',
                content: 'Second-content',
                },
                {
                title: '课程内容',
                content: 'Last-content',
                },
            ],
            majorList:[],
            moduleList:[],
            quillInfo:'',
            courseData:{},
            catalog:[],
            cataModal:false,
            type:0,//0是新增 1修改
            defaultAuthValue:'',
            catafields:null,
            isAddChapter:0,//0新增  1修改
            chapterId:null,//当前选中的章节ID
            addOrInsert:0,//0是新增到最后面 1是插入
            insertRank:null,
            taskModal:false,
            taskfields:null,
            taskTypeList:[
                {
                    id:1,
                    name:'视频'
                },{
                    id:2,
                    name:'资料'
                },{
                    id:3,
                    name:'习题'
                },{
                    id:4,
                    name:'考试'
                },{
                    id:5,
                    name:'题库训练'
                }
            ],
            apiUrl:window.g.apiUrl,
            headers: {authorization: 'authorization-text'},
            taskType:'',
            fileUrl:'',
            addTaskInfo:{},
            currentCataId:null,
            isAddTask:0,//0新增 1修改
            title:'',
            fileType:null,//资料类型 0视频 1资料 2习题 3考试
            isVisible:false,
            paperModal:false,
            columns,
            paperList:[],
            pagination:{pageSize:10,total:10,current:1},
            searchInfo:{
                page:1,
                pageSize:10,
                keyword:'',
                major:[],
            },
            duringModuleList:[],
            selectPaperInfo:null,//选中试卷的信息
            moduleModal:false,
            moduleColumns,
            moduleTableList:[],
            modulePagination:{pageSize:10,total:0},
            addModuleModal:false,
            modulefields:{},
            selectMajor:"专业方向",
            selectTask:'任务类型',
            selectExamType:undefined,
            fileList:[],
            taskId:'',
            courseId:null,
            isSelectModule:false,
            ExamTypeList:[
                {
                    'name':'理论考试',
                    'id':0
                },{
                    'name':'实操考试',
                    'id':1
                },{
                    'name':'理论考试+实操考试',
                    'id':2
                }
            ],
            isLoading:false,//视频是否上传完
            videoUrl:'',
            player:null,
            waitUploadingLoading:false,
            paperOrItem:false,//判断是试卷还是题库
            selectItemModal:false,
            itemList:[],//题库列表
            itemPagination:{pageSize:10,total:0,current:1},
            itemSearchInfo:{
                page:1,
                pageSize:10,
                keyword:'',
                majorId:''
            },
            defaultTime:[],
            format:'YYYY-MM-DD HH:mm:ss'
        }
    },
    methods:{
        moment,
        editInit(id){
            this.type=1
            this.courseId=id
            this.getToken(getMajorListApi,{},res=>{
                this.majorList=res.data
                    this.getToken(getCourseDetailApi,{'courseId':this.courseId},res=>{
                    this.fields=res.data
                    this.moduleList=this.majorList.filter(item=>item.id==(res.data.majors)[0].id)[0].children
                    this.fields.major=res.data.majors[0].id
                    this.fields.module=res.data.majors[1].id
                    this.defaultAuthValue=res.data.authentation
                    this.imageUrl=res.data.cover
                    this.quillInfo=res.data.courseInfo
                    this.catalog=res.data.chapters
                    this.currentCataId=this.catalog[0].id
                })
            })
        },
        getUrl(data){
            this.$refs.form.form.setFieldsValue({['cover']:data})
            this.imageUrl=data
        },
        handleMajor(id,type){
            if(type==0){
                this.moduleList=this.majorList.filter(item=>item.id==id)[0].children
                this.$refs.form.form.resetFields(['module'])
            }else if(type==1){
                let arr=Object.assign(this.duringModuleList);
                this.moduleTableList=arr.filter(item=>(item.majorId==id)).map((item,index)=>({...item,index:index+1}))
                this.modulePagination.total=this.moduleTableList.length
                this.selectMajor=id
            }
        },
        changeAuth(data){
            this.$refs.form.form.setFieldsValue({['authentation']:data})
        },
        next(){
            if(this.current==0){
                this.$refs.form.form.validateFields().then(res=>{
                    let api
                    let formData={...res,majorId:[res.major,res.module],'authentation':Array.isArray(res.authentation)?res.authentation.join():res.authentation}
                    if(this.type==0){
                        api=submitCourseApi
                    }else{
                        api=updateCourseApi
                        formData={...formData,'courseId':this.courseId}
                    }
                    this.getToken(api,formData,data=>{
                        this.courseId=data.data.courseId
                    })
                    this.current++;
                })
            }else if(this.current==1){
                if(this.quillInfo){
                    this.getToken(updateCourseApi,{'courseId':this.courseId,'courseInfo':this.quillInfo},()=>{
                        this.current++
                    })
                }else{
                    this.$message.error('课程简介不能为空')
                }
            }
        },
        prev(){
            this.current--;
        },
        getQuillContent(data){
            this.quillInfo=data
        },
        openCata(data,rank){
            this.isAddChapter=0  
            this.addOrInsert=data
            this.cataModal=true
            this.insertRank=rank
            this.catafields=null
        },
        addCata(){
            if(this.catalog.length>=100){
                this.$message.error('最多上传100节')
                return
            }
            this.$refs.cataForm.form.validateFields().then(res=>{
                let api
                let formData=res
                if(this.isAddChapter==0){
                    api=addChapterApi
                    formData={'title':res.chapter,'courseId':this.courseId,'rank':this.addOrInsert==0?'':this.insertRank}
                }else{
                    api=updateChapterApi
                    formData={'title':res.chapter,'chapterId':this.chapterId}
                }
                this.getToken(api,formData,()=>{
                    this.$message.success('操作成功')
                    this.updateChapter()
                    this.cataModal=false
                })
            })
        },
        updateChapter(){
            this.getToken(getCourseDetailApi,{'courseId':this.courseId},res=>{
                this.catalog=res.data.chapters
            })
        },
        // 目录章节的操作
        toggle(item){
            this.currentCataId=item
        },
        editChapter(item){
            this.isAddChapter=1
            this.catafields={'chapter':item.title}
            this.cataModal=true
            this.chapterId=item.id
        },
        deleteChapter(id){
            this.getToken(deleteChapterApi,{'chapterId':id},()=>{
                this.$message.success('已删除')
                this.updateChapter()
            })
        },
        // 任务的操作
        openTaskModal(data,taskRank){
            this.isLoading=false
            this.changeTask(1)
            this.isAddTask=0
            this.addTaskInfo={...data,taskRank}
            this.taskModal=true
            this.title=data.title
            this.selectPaperInfo=null
            this.taskfields=null
            this.fileList=[]
        },
        cancelModal(){
            this.taskModal=false
            this.handleRemove()
        },
        handleRemove(){
            if(this.isAddTask==0){
                this.fileList=[]
                this.$refs.taskForm.form.resetFields(['file'])
            }else{
                this.fileList=[]
                this.$refs.taskForm.form.setFieldsValue({['file']:this.fields.file})
            }
            this.isLoading=false
        },
        onUploadSucceed(){
            this.waitUploadingLoading=false
        },
        waitUploading(){
            this.waitUploadingLoading=true
        },
        handleChange(info) {
            // 控制只允许传一个
            this.isLoading=true
            let fileList = [...info.fileList];
            fileList = fileList.slice(-2);
            fileList = fileList.map(file => {
                if (file.response) {
                file.url = file.response.url;
                }
                return file;
            });
            this.fileList = fileList.splice(FileList.length-1);

            // 如果修改的时候是删除，更新form状态
            if(info.fileList.length==0){
                this.$refs.taskForm.form.resetFields(['file'])
                return
            }
            this.taskType==this.fileType==1?'video':'document'
            if (info.file.status === 'done') {
                this.isLoading=false
                this.$message.success(`${info.file.name} 上传成功`);
                this.fileUrl=info.file.response.data.fileUrl
                this.$refs.taskForm.form.setFieldsValue({['file']:this.fileUrl})
                
            } else if (info.file.status === 'error') {
                this.isLoading=false
                this.$message.error(`${info.file.name} 上传失败`);
                this.waitUploadingLoading=false
            }
        },
        addTask(){
            if(this.waitUploadingLoading){
                this.$message.error("请先上传视频")
                return
            }
            this.$refs.taskForm.form.setFieldsValue({['type']:this.fileType})
            if(this.fileType==4){
                this.$refs.taskForm.form.setFieldsValue({['examType']:this.selectExamType})
            }
            this.$refs.taskForm.form.validateFields().then(res=>{
                let api
                let formData={
                    ...res,
                    'chapterId':this.addTaskInfo.id,
                    'rank':this.addTaskInfo.taskRank
                }
                if(this.fileType==1){
                    formData={...formData,'resourceUrl':localStorage.getItem('videoUrl'),'type':0}
                }else if(this.fileType==2){
                    formData={...formData,'resourceUrl':this.fileUrl,'type':1}
                }else if(this.fileType==3){
                    formData={...formData,'type':2}
                }else{
                    if(this.paperOrItem){
                        if(formData.examTime){
                            if(formData.examTime[0]&&formData.examTime[1]){
                                formData={...formData,'type':3,'examStart':formData.examTime[0],'examEnd':formData.examTime[1]}
                            }else{
                                if(!formData.examTime[0]&&!formData.examTime[1]){
                                    formData={...formData,'type':3,'examStart':null,'examEnd':null}
                                }else{
                                    this.$message.error('开始时间或结束时间不能为空')
                                    return;
                                }
                            }
                        }else{
                            formData={...formData,'type':3,'examStart':null,'examEnd':null}
                        }
                    }else{
                        formData={...formData,'type':4,'questionLibId':formData.paperId,'paperId':undefined}
                    }
                }
                if(this.taskfields){
                    api=editTaskApi
                    formData={...formData,'taskId':this.taskId}
                }else{
                    api=addTaskApi
                }
                this.getToken(api,formData,()=>{
                    this.taskModal=false
                    this.$message.success('操作成功')
                    this.updateChapter()
                    localStorage.setItem('videoUrl','')
                })
            })
        },
        editTask(item){
            this.taskId=item.id
            this.taskModal=true;
            this.isAddTask=1;
            this.selectTask=item.type+1
            this.changeTask(this.selectTask)
            if(this.selectTask==4){
                this.changeExamType(item.examType)
            }
            this.taskfields=item
            this.fileList=[]
            this.taskfields.file=item.resourceUrl
            localStorage.setItem('videoUrl',item.resourceUrl)
            if(this.selectTask==1||this.selectTask==2){
                let urlArr=item.resourceUrl.split('/')
                urlArr[urlArr.length-1]
                this.fileList.push({
                    uid: '1',
                    name: urlArr[urlArr.length-1],
                    status: 'done',
                    url: item.resourceUrl,
                })
                this.fileUrl=item.resourceUrl
            }else{
                if(this.paperOrItem){//试卷
                    if(item.examStart){
                        this.defaultTime=[moment(item.examStart),moment(item.examEnd)]
                        this.taskfields.examTime=[item.examStart,item.examEnd]
                    }else{
                        this.defaultTime=[undefined,undefined]
                        this.taskfields.examTime=[null,null]
                    }
                    this.getToken(getTestList,{...this.searchInfo,'type':this.selectTask==3?0:1},res=>{
                        this.selectPaperInfo=res.data.rows.filter(value=>value.id==item.paperId)[0]
                    })
                }else{
                    this.getToken(getQuestionList,{},res=>{
                        this.selectPaperInfo=res.data.rows.filter(value=>value.id==item.questionLibId)[0]
                    })
                }
                
            }
        },
        deleteTask(id){
            this.getToken(deleteTaskApi,{'taskId':id},()=>{
                this.$message.success('已删除')
                this.updateChapter()
            })
        },
        setFree(value){
            this.getToken(updateTaskApi,{'taskId':value.id,'isFree':value.isFree==0?1:0},res=>{
                this.$message.success(res.message)
                this.updateChapter()
            })
        },
        taskMove(id,arrow){
            this.getToken(moveTaskApi,{'taskId':id,'moveTo':arrow},res=>{
                this.$message.success(res.message)
                this.updateChapter()
            })
        },
        changeTask(data){
            this.selectExamType=undefined
            this.selectPaperInfo=null
            this.taskFormData=[
                {
                    label:"任务类型",
                    scopedSlots: { customRender: 'taskType'},
                },{
                    label:"任务名称",
                    prop:"title",
                    placeholder:'请输入任务名称',
                    rules:[{required:true,message:'请输入任务名称'}],
                },{
                    label:"资源上传",
                    isVisible:false,
                    scopedSlots: { customRender: 'taskResource'},
                },{
                    label:"测试说明",
                    isVisible:true,
                    scopedSlots: { customRender: 'test'},
                },{
                    label:"试题选择",
                    isVisible:true,
                    scopedSlots: { customRender: 'exam'},
                }
            ]
            if(data==1||data==2){
                this.taskFormData[2].isVisible=false
                this.taskFormData[3].isVisible=true
                this.taskFormData[4].isVisible=true
                if(data==1){
                    this.accept='.mp4'
                }else{
                    this.accept='.xls, .xlsx, .doc, .docx, .pdf, .ppt, .pptx'
                }
            }else if(data==4){
                this.paperOrItem=true
                this.taskFormData=[
                    {
                        label:"任务类型",
                        scopedSlots: { customRender: 'taskType'},
                    },{
                        label:"考试类型",
                        scopedSlots: { customRender: 'examType'},
                    },{
                        label:"考试名称",
                        prop:"title",
                        placeholder:'请输入任务名称',
                        rules:[{required:true,message:'请输入任务名称'}],
                    },{
                        label:"考试时间",
                        scopedSlots: { customRender: 'examTime'},
                    },{
                        label:"考试说明",
                        scopedSlots: { customRender: 'test'},
                    },{
                        label:"理论考试",
                        isVisible:true,
                        scopedSlots: { customRender: 'exam'},
                    },{
                        label:"实操考试",
                        isVisible:true,
                        scopedSlots: { customRender: 'operationExam'},
                    }
                ]
            }else{
                if(data==5){
                    this.paperOrItem=false
                    this.taskFormData[3].label='任务说明'
                    this.taskFormData[4].label='题库选择'
                    this.selectPaperInfo=null
                }else{
                    this.paperOrItem=true
                    this.taskFormData[3].label='测试说明'
                    this.taskFormData[4].label='试题选择'
                    this.selectPaperInfo=null
                }
                this.taskFormData[2].isVisible=true
                this.taskFormData[3].isVisible=false
                this.taskFormData[4].isVisible=false
            }
            this.selectTask=data
            this.fileType=data
            this.taskType=this.fileType==1?'video':'document'
        },
        // 打开题库模态框
        selectItem(){
            this.getToken(getQuestionList,this.itemSearchInfo,res=>{
                this.itemList=res.data.rows.map((item,index)=>({...item,'index':(this.itemSearchInfo.page-1)*10+index+1}))
                this.itemPagination.total=res.data.count
                this.selectItemModal=true
            })
        },
        // 题库列表
        getItemList(){
            this.getToken(getQuestionList,this.itemSearchInfo,res=>{
                this.itemList=res.data.rows.map((item,index)=>({...item,'index':(this.itemSearchInfo.page-1)*10+index+1}))
                this.itemPagination.total=res.data.count
            })
        },
        // 选择题库
        isSelectItem(data){
            this.$confirm({
                title: '确认选中“'+data.title+'”题库吗?',
                cancelText:"取消",
                okText:'确定',
                onOk:()=>{
                    this.selectItemModal=false
                    this.selectPaperInfo=this.itemList.filter(item=>item.id==data.id)[0]
                    this.$refs.taskForm.form.setFieldsValue({['paperId']:data.id})
                },
                onCancel() {
                },
            });
        },
        // 题库翻页
        changeItemPage(data){
            this.itemSearchInfo.page=data.current
            this.itemPagination.current=data.current
            this.getItemList()
        },
        // 查询题库
        submitItemSearch(data){
            this.itemSearchInfo.keyword=data.keyword
            this.itemSearchInfo.page=1
            this.itemPagination.current=1
            if(data.moduleId&&data.moduleId!=0){
                this.itemSearchInfo.majorId=data.moduleId
            }else{
                this.itemSearchInfo.majorId=data.majorId==0?null:data.majorId
            }
            this.getItemList()
        },
        // 更改考试时间
        changeTime(start,end){
            this.$refs.taskForm.form.setFieldsValue({['examTime']:[start?moment(start).format(this.format):null,end?moment(end).format(this.format):null]})
        },
        // 预览题库
        previewItem(){

        },
        changeExamType(data){
            this.selectExamType=data
            if(data==0){
                this.taskFormData[5].isVisible=false
                this.taskFormData[6].isVisible=true
            }else if(data==1){
                this.taskFormData[5].isVisible=true
                this.taskFormData[6].isVisible=false
            }else{
                this.taskFormData[5].isVisible=false
                this.taskFormData[6].isVisible=false
            }
        },
        previewTest(id){
            let query
            if(this.paperOrItem){
                query={id}
            }else{
                query={id,'isItem':true}
            }
            let routeData = this.$router.resolve({
                path: "/paperPreview",
                query: query
                });
                let width=800
                let left=parseInt((screen.availWidth/2) - (width/2))
                window.open(routeData.href, '_blank',"height=800, width="+width+", toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no,top=50,left="+left);
        },
        changePage(data){
            this.searchInfo.page=data.current
            this.pagination.current=data.current
            this.getPaperList()
        },
        getPaperList(){
            this.getToken(getTestList,{...this.searchInfo,'type':this.fileType==3?0:1},res=>{
                this.paperList=res.data.rows.map((item,index)=>({...item,'index':(this.searchInfo.page-1)*10+index+1}))
                this.pagination.total=res.data.count
            })
        },
        selectPaper(){
            this.getPaperList()
            this.paperModal=true
        },
        removePaper(){
            this.$confirm({
                title: '确认移除该'+(this.paperOrItem?'试卷':'题库')+'吗?',
                cancelText:"取消",
                okText:'确定',
                onOk:()=>{
                    this.selectPaperInfo=null
                    this.$refs.taskForm.form.setFieldsValue({['paperId']:undefined})
                },
                onCancel() {
                },
            });
        },
        isSelect(record){
            this.$confirm({
                title: '确认选中“'+record.title+'”试卷吗?',
                cancelText:"取消",
                okText:'确定',
                onOk:()=>{
                    this.paperModal=false
                    this.selectPaperInfo=this.paperList.filter(item=>item.id==record.id)[0]
                    this.$refs.taskForm.form.setFieldsValue({['paperId']:record.id})
                },
                onCancel() {
                },
            });
        },
        save(){
            this.$message.success('操作成功')
            this.$router.push({path:'/course'})
        },
        submitSearch(data){
            this.searchInfo.keyword=data.keyword
            this.searchInfo.page=1
            this.pagination.current=1
            if(data.moduleId&&data.moduleId!=0){
                this.searchInfo.majorId=data.moduleId
            }else{
                this.searchInfo.majorId=data.majorId==0?null:data.majorId
            }
            this.getPaperList()
        },
        openModuleModal(){
            this.moduleModal=true
            this.getModuleList()
        },
        cancelModule(){
            this.moduleModal=false
            this.getToken(getMajorListApi,{},res=>{
                this.majorList=res.data
                this.$refs.form.form.setFieldsValue({['module']:undefined})
                let major=this.$refs.form.form.getFieldsValue(['major'])
                this.moduleList=this.majorList.filter(item=>item.id==major.major)[0].children
            })
        },
        getModuleList(){
            this.getToken(getMajorListApi,{},res=>{
                let arr=res.data.map(item=>({...item,'children':item.children.map(value=>({...value,'major':item.name,'majorId':item.id}))}))
                this.moduleTableList=[]
                arr.forEach(item=>{
                    this.moduleTableList.push(item.children)
                })
                this.duringModuleList=this.moduleTableList=this.moduleTableList.reduce((prev,next)=>{
                    return [...prev,...next]
                }).map((item,index)=>({...item,index:index+1}))
                if(this.selectMajor&&this.selectMajor!='专业方向'){
                    this.moduleTableList=this.moduleTableList.filter(item=>(item.majorId==this.selectMajor)).map((item,index)=>({...item,index:index+1}))
                }
                this.modulePagination.total=this.moduleTableList.length
            })
        },
        editModule(item){
            this.isSelectModule=false
            this.addModuleModal=true
            this.modulefields={'major':item.majorId,'module':item.name,'majorId':item.id}
            this.getToken(checkModuleApi,{'majorId':item.id},res=>{
                if(res.used){
                    this.isSelectModule=true
                }
            })
        },
        openAddModuleModal(){
            this.isSelectModule=false
            this.modulefields=null
            this.addModuleModal=true
        },
        addModule(){
            this.$refs.moduleForm.form.validateFields().then(res=>{
                let api
                let formData={'pid':res.major,'name':res.module}
                if(this.modulefields){
                    api=editModuleApi
                    formData={...formData,'majorId':this.modulefields.majorId}
                }else{
                    api=addModuleApi
                }
                this.getToken(api,formData,data=>{
                    this.$message.success(data.message)
                    this.addModuleModal=false
                    this.getModuleList()
                })
            })
        },
        deleteModule(id){
            this.getToken(deleteModuleApi,{'majorId':id},res=>{
                this.$message.success(res.message)
                this.openModuleModal()
            })
        },
        returnBack(){
            let isReturn=()=>{
                this.$confirm({
                    title: '数据没有保存，确定返回吗?',
                    cancelText:"取消",
                    okText:'确定',
                    onOk:()=>{
                        this.$router.go(-1)
                    },
                    onCancel() {
                    },
                });
            }
            let isFlag=false
            if(this.current==0){
                if(this.type==0){
                    let data=this.$refs.form.form.getFieldsValue()
                    if(JSON.stringify(data)=="{}"){
                        this.$router.go(-1)
                        return
                    }else{
                        isFlag=true
                    }
                }else{
                    let data=this.$refs.form.form.getFieldsValue()
                    delete this.fields.chapters
                    delete this.fields.courseInfo
                    delete this.fields.majors
                    delete this.fields.id
                    this.fields={
                        'title':this.fields.title,
                        'cover':this.fields.cover,
                        'major':this.fields.major,
                        'module':this.fields.module,
                        'teacher':this.fields.teacher,
                        'teacherInfo':this.fields.teacherInfo,
                        'authentation':this.fields.authentation
                    }
                    if(JSON.stringify(this.fields) === JSON.stringify(data)){
                        this.$router.go(-1)
                        return
                    }else{
                        isFlag=true
                    }
                }
            }else{
                isFlag=true
            }
            if(isFlag){
                isReturn()
            }
        },
        // 预览
        previewTask(item){
            if(item.type==2||item.type==3||item.type==4){//习题和考试
                    let query
                    if(item.type==4){
                        query={'id':item.questionLibId,'isItem':true}
                    }else{
                        query={'id':item.paperId}
                    }
                    let routeData = this.$router.resolve({
                        path: "/paperPreview",
                        query: query
                    });
                let width=800
                let left=parseInt((screen.availWidth/2) - (width/2))
                window.open(routeData.href, '_blank',"height=800, width="+width+", toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no,top=50,left="+left);
            }else if(item.type==0){//视频
                this.$router.push({path:'/previewVideo',query:{id:item.resourceUrl}})
            }else{
                let width=800
                let left=parseInt((screen.availWidth/2) - (width/2))
                window.open(item.resourceUrl, '_blank',"height=800, width="+width+", toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no,top=50,left="+left);
            }
        },
    }
}
</script>
<style lang="stylus">
.courseAdd
    .top
        position:relative
        .returnBack
            position:absolute;
            top:-78px;
            right:-21px;
    .ant-upload.ant-upload-select-picture-card
        width:286px;
        height:160px;
        .ant-upload
            padding:0;
    .eUpload 
        img
            width:286px;
            height:160px;
            max-height:160px;
    .innerCommon
        .module
            display:flex;
            justify-content:space-between
            .moduleManager
                margin-left:10px;
        .content
            .wrapHeader
                height:105px;
                .right
                    width:100%
        .steps-action
            border-top:1px solid #ddd;
            padding-top:45px;
            text-align:center;
            button  
                width:200px;
        .catalog
            .bottomBtn
                margin-bottom:20px;
                margin-top:10px;
            .empty
                text-align:center;
                padding:100px;
                button
                    margin-bottom:30px;
            .cataTop
                border-left:2px solid #40a9ff
                margin-bottom:20px;
                padding-left:10px;
            .cataBox
                .cataTitle 
                    background:#F5F7FA;
                    margin-bottom:10px;
                    line-height:40px;
                    justify-content:space-between;
                    display:flex;
                    align-items:center; 
                    &:hover
                        box-shadow:0 0 10px #ccc;
                        span
                            display:inline-block
                    b
                        display:inline-block;
                        width:120px;
                        text-align:center;
                    span
                        display:inline-block;
                        cursor:pointer;
                        padding:0 10px;
                        display:none;
                        &:hover
                            color:#096dd9

            .taskList
                margin-bottom:10px;
                padding:0 40px;
                .taskBox
                    margin:0;
                    border-bottom:1px dashed #ddd;
                    line-height:40px;
                    justify-content:space-between;
                    display:flex;
                    align-items:center; 
                    .right
                        span
                            padding:0 10px;
                            display:none;
                            cursor:pointer;
                            &:hover
                                color:#096dd9
                    &:hover
                        box-shadow:0 0 10px #ddd;
                        .right
                            span
                                display:inline-block
            
.courseAddModal
    .selectTask
        top:37px;
        left:187px;
        width:470px;
        z-index:3;
    .taskTypeTips
        position absolute
        color red
        top:150px;
        left:216px;
        font-size 12px
        width:470px;
    .taskType
        width:470px;
        height:40px;
    #eform
        .ant-col-6
            width:25%
    .selectPaper
        display:flex;
        background:#eee;
        justify-content:space-between;
        padding:0 10px;
        overflow:hidden;
        text-overflow:ellipsis;
        white-space:nowrap;
        .deletePaper
            color:#40a9ff;
            font-weight:normal;
            display:inline-block;
            margin-left:10px;
            cursor:pointer;
    .selectExamType
        position:absolute;
        top:180px;
        left:211px;
        width:470px;
        z-index:3;
    .examType
        width:470px;
        height:40px;
    .has-success.has-feedback
        .ant-form-item-children-icon
            right:-28px;
.paperModal
    .body
        .header
            padding-bottom:25px;
.moduleModal
    .header
        padding-bottom:20px;
</style>